<template>
	<div class="padding-across-10" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
		<div style="width: 100%">
			<el-row type="flex">
				<el-col :span="2">
					<headerOpreate style="width: 30px;padding: 5px 0" :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
				</el-col>
				<el-col :span="22">
					<div style="padding-top:5px;width:900px;float: left">
						<span style="font-size: 13px;font-weight: bold">读者证号</span>
						<el-input v-model="readerCode" style="width: 150px" size="small"></el-input>
						<el-button type="primary" size="small" @click="findUnReturnInfo"><i class="el-icon el-icon-search el-icon--left"></i>查询</el-button>
					</div>
				</el-col>
			</el-row>
		</div>

		<!-- 查询的读者信息 -->
		<el-table border style="width: 100%;" :data="readerInfo">
			<el-table-column :show-overflow-tooltip="true" label="读者姓名" align="center" prop="name"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="读者证号" align="center" prop="code"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="读者标签" align="center" prop="tag"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="角色" align="center" prop="type"></el-table-column>
			<!-- <el-table-column :show-overflow-tooltip="true" label="所属区域" align="center" prop="district"></el-table-column> -->
			<el-table-column :show-overflow-tooltip="true" label="借阅期限(天)" align="center" prop="borrowdaylimit"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="借书上限(册)" align="center" prop="holdlimit"></el-table-column>
		</el-table>

		<el-tabs v-model="activeName" @tab-click="handleClick" v-if="readerInfo.length > 0">
			<el-tab-pane label="读者在借书籍" name="first">
				<div style="width: 140px;float: left">
					<!-- <el-button type="primary" size="small" @click="renewBook"><i class="el-icon el-icon-document el-icon--left"></i>续借</el-button> -->
					<el-button type="danger" size="small" @click="returnBook"><i class="el-icon el-icon-eleg-icon_documents_alt el-icon--left"></i>还书</el-button>
				</div>
				<div class="block" style="text-align:right;">
					<el-pagination @current-change="handleUnReturnCurrentChange" @size-change="handleUnReturnSizeChange" :current-page="unReturnCurrentPage" :page-size="unReturnPageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="unReturnTotalSize">
					</el-pagination>
				</div>
				<el-table border style="width: 100%;" @selection-change="handleUnReturnSelectionChange" :data="unReturnTableData">
					<el-table-column :show-overflow-tooltip="true" type="selection"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="书名" align="center" prop="Name"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="条码" align="center" prop="BookBarcode"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="借阅时间" align="center" prop="BorrowTime"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="到期时间" align="center" prop="DueTime"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="状态" align="center">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.IsOverDue" type="danger">超期</el-tag>
							<el-tag v-else type="success">正常</el-tag>
						</template>
					</el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="是否归还" align="center">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.IsReturn" type="success">已归还</el-tag>
							<el-tag v-else type="warning">未归还</el-tag>
						</template>
					</el-table-column>
				</el-table>
				<div class="block" style="text-align:right;margin-bottom:100px;">
					<el-pagination @current-change="handleUnReturnCurrentChange" @size-change="handleUnReturnSizeChange" :current-page="unReturnCurrentPage" :page-size="unReturnPageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="unReturnTotalSize">
					</el-pagination>
				</div>
			</el-tab-pane>

			<el-tab-pane label="馆藏地在库书籍" name="second">
				<div>
					<div>
						<el-button style="margin-right: 3px" type="primary" size="small" @click="borrowBook"><i class="el-icon el-icon-eleg-icon_documents_alt el-icon--left"></i>借书</el-button>
					</div>
					<div style="float: left;padding-top: 2px">
						<span style="font-size: 13px;font-weight: bold">检索字段</span>
						<el-select size="small" v-model="value" :placeholder="$t('message.selectModeAlert')" style="width: 90px;margin-right: 2px" @change="selectType">
							<el-option label="关键字" :value="0"></el-option>
							<el-option label="条码" :value="1"></el-option>
							<el-option label="标签" :value="2"></el-option>
						</el-select>
						<span style="font-size: 13px;font-weight: bold">关键字</span>
						<el-autocomplete size="small" style="width: 190px;" class="inline-input" v-model="keyWord" :fetch-suggestions="querySearch" :placeholder="contentHint" @select="handleSelect">
							<el-button id="searchBookData" slot="append" icon="search" @click="findBookOnInfo"></el-button>
						</el-autocomplete>
					</div>
					<div class="block" style="text-align:right;">
						<el-pagination @current-change="handleBookOnCurrentChange" @size-change="handleBookOnSizeChange" :current-page="currentBookOnPage" :page-size="pageBookOnSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalBookOnSize">
						</el-pagination>
					</div>
				</div>
				<el-table border style="width: 100%;" @selection-change="handleBookOnSelectionChange" :data="bookOnTableData">
					<el-table-column :show-overflow-tooltip="true" type="selection"></el-table-column>
					<el-table-column label="书名" align="center" prop="Name"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="条码" align="center" prop="BookBarcode"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="标签" align="center" prop="RFIDTag"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="索引号" align="center" prop="LocalCallNumber"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="最近还书时间" align="center" prop="ReturnTime"></el-table-column>
					<el-table-column :show-overflow-tooltip="true" label="状态" align="center" width="100">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.Status === 3" type="success">在库</el-tag>
							<el-tag v-else type="warning">外借</el-tag>
						</template>
					</el-table-column>
				</el-table>
				<div class="block" style="text-align:right;margin-bottom:100px;">
					<el-pagination @current-change="handleBookOnCurrentChange" @size-change="handleBookOnSizeChange" :current-page="currentBookOnPage" :page-size="pageBookOnSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalBookOnSize">
					</el-pagination>
				</div>
			</el-tab-pane>
		</el-tabs>

		<!-- 还书结果展示 -->
		<el-dialog title="还书信息" v-model="returmBookResultDialog" size='large'>
			<el-table border style="width: 100%;" :data="returnBookResultData">
				<el-table-column :show-overflow-tooltip="true" type="index"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="书名" align="center" prop="name"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="条码" align="center" prop="barcode"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="标签" align="center" prop="tag"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="借阅时间" align="center" prop="borrowtime"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="还书时间" align="center" prop="realreturntime"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="结果" align="center">
					<template slot-scope="scope">
						<el-tag type="success" v-if="scope.row.code === 0">还书成功</el-tag>
						<el-tag v-else type="danger">{{scope.row.msg}}</el-tag>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
		<!-- 借书结果展示 -->
		<el-dialog title="借书信息" v-model="borrowBookResultDialog" size='large'>
			<el-table border style="width: 100%;" :data="borrowBookResultData">
				<el-table-column :show-overflow-tooltip="true" type="index"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="书名" align="center" prop="name"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="条码" align="center" prop="barcode"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="标签" align="center" prop="tag"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="借阅时间" align="center" prop="borrowtime"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="到期时间" align="center" prop="duetime"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="结果" align="center">
					<template slot-scope="scope">
						<el-tag type="success" v-if="scope.row.code === 0">借书成功</el-tag>
						<el-tag v-else type="danger">{{scope.row.msg}}</el-tag>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../../assets/js/common.js'
	import headerOpreate from '../../../../../components/headerOpreate'
	let id = 1000;
	var date = new Date();
	export default {
		components: {
			headerOpreate
		},
		data() {
			//回车触发查询按钮
			document.onkeydown = function(event) {
				var e = event || window.event;
				if(e && e.keyCode == 13) { //回车键的键值为13
					$("#searchBookData").click();
				}
			};
			Date.prototype.format = function(format) {
				var date = {
					"M+": this.getMonth() + 1,
					"d+": this.getDate()
				};
				if(/(y+)/i.test(format)) {
					format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				for(var k in date) {
					if(new RegExp("(" + k + ")").test(format)) {
						format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
							date[k] : ("00" + date[k]).substr(("" + date[k]).length));
					}
				}
				return format;
			}
			return {
				locationData: [],
				locationId: 0,
				isReload: false,
				startTime: new Date((date.getTime() - 3600 * 1000 * 24 * 7)).format('yyyy-MM-dd') + ' 00:00:00',
				endTime: date.format('yyyy-MM-dd') + ' 23:59:59',
				loading: false,
				value: 0,
				contentHint: '书名/作者 查询',
				searchHistory: [],
				item: {},
				holdLimit: 0, //借阅上限
				borrowBookResultDialog: false,
				borrowBookResultData: [],
				returmBookResultDialog: false,
				returnBookResultData: [],
				activeName: 'first',
				typeRadio: 0, //类型
				bookType: 0,
				readerCode: '',
				readerInfo: [],
				readerInfoName: '',
				readerInfoTag: '',
				unReturnTableData: [],
				multipleUnReturnSelection: [],
				unReturnCurrentPage: 1,
				unReturnPageSize: 10,
				unReturnTotalSize: 0,
				bookOnTableData: [],
				multipleBookOnSelection: [],
				currentBookOnPage: 1,
				pageBookOnSize: 10,
				totalBookOnSize: 0,
				keyWord: '',
				showUpdate: false,
				opreateDatas: [{
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: '刷新',
					action: 'reloadDatas'
				}]
			}
		},
		props: {
			subArgs: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			handleUnReturnCurrentChange(val) {
				this.unReturnCurrentPage = val;
				this.findUnReturnInfo();
			},
			handleUnReturnSizeChange(val) {
				this.unReturnPageSize = val;
				this.findUnReturnInfo();
			},
			handleUnReturnSelectionChange(val) {
				this.multipleUnReturnSelection = val;
			},
			handleBookOnCurrentChange(val) {
				this.currentBookOnPage = val;
				this.findBookOnInfo();
			},
			handleBookOnSizeChange(val) {
				this.pageBookOnSize = val;
				this.findBookOnInfo();
			},
			handleBookOnSelectionChange(val) {
				this.multipleBookOnSelection = val;
			},
			querySearch(queryString, cb) {
				var restaurants = this.searchHistory;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			createFilter(queryString) {
				return(restaurant) => {
					return(restaurant.value.indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleSelect(item) {
				// console.log(item);
			},
			handleClick(tab, event) {
				if(tab.name === 'first') {
					this.activeName = 'first';
					this.getUnReturnBookData();
				} else {
					this.activeName = 'second';
					// this.getLocationByUser();
					this.findBookOnInfo();
				}
			},
			//选择馆藏地查询在库图书
			selectLocation(){
				this.findBookOnInfo();
			},
			selectType() {
				if(this.value === 0) {
					this.contentHint = '书名/作者 查询';
				} else if(this.value === 1) {
					this.contentHint = '请输入完整图书条码';
				} else {
					this.contentHint = '请输入完整图书标签';
				}
			},
			formateUnReturnSelection() {
				var result = [],
				array = this.multipleUnReturnSelection;
				for(var i = 0; i < array.length; i++) {
					result[i] = {};
					result[i].tag = array[i].RFIDTag;
					result[i].status = 2;
				}
				return result;
			},
			formateBookOnSelection() {
				var result = [],
				array = this.multipleBookOnSelection;
				for(var i = 0; i < array.length; i++) {
					result[i] = {};
					result[i].tag = array[i].RFIDTag;
					result[i].status = 1;
				}
				return result;
			},
			//借书
			borrowBook() {
				if(this.formateBookOnSelection().length > 0) {
					// if(this.formateBookOnSelection().length > (this.holdLimit - this.unReturnTotalSize)) {
					// 	this.$notify.error({
					// 		title: '错误',
					// 		message: '超过借阅上限',
					// 		duration: 2500
					// 	});
					// } else {
						this.$confirm('此操作将进行批量借书，是否继续?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.loading = true;
							HttpServer.httpPost.call(this, '/Api/Reader/Circulate', {
								code: this.readerCode,
								tag: this.readerInfoTag,
								sn: '',
								ReaderName: this.readerInfoName,
								books: this.formateBookOnSelection()
							}, function(resp) {}, function(resp) {
									// console.log('借书',resp);
									this.loading = false;
									if(resp.data.code === 0) {
										//弹窗显示借书结果
										this.borrowBookResultDialog = true;
										this.borrowBookResultData = resp.data.books;
										this.findUnReturnInfo();
										this.findBookOnInfo();
									} else {
										this.$notify.error({
											title: '错误',
											message: response.data.msg,
											duration: 2500
										});
									}

								});
						}).catch(() => {
							this.$notify.info({
								title: '消息',
								message: this.$t('message.operationCanceled'),
								duration: 2500
							})
						})
					// }
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择批量操作的图书',
						type: 'warning',
						duration: 2500
					});
				}
			},
			//还书
			returnBook() {
				if(this.formateUnReturnSelection().length > 0) {
					this.$confirm('此操作将进行批量还书，是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.loading = true;
						HttpServer.httpPost.call(this, '/Api/Reader/Circulate', {
							code: this.readerCode,
							tag: this.readerInfoTag,
							sn: '',
							ReaderName: this.readerInfoName,
							books: this.formateUnReturnSelection()
						}, function(response) {}, function(response) {
							this.loading = false;
							if(response.data.code === 0) {
								// console.log('还书',response)
								this.returmBookResultDialog = true;
								this.returnBookResultData = response.data.books;
								this.getUnReturnBookData();
								// console.log('this.returnBookResultData',this.returnBookResultData)
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						})
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.operationCanceled'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择批量操作的图书',
						type: 'warning',
						duration: 2500
					});
				}
			},
			//续借
			renewBook() {

			},
			//去掉读者未归还时间中的T
			formateData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].BorrowTime.indexOf("T");
					var index2 = array[i].DueTime.indexOf("T");
					array[i].BorrowTime = array[i].BorrowTime.substring(0, index1) + " " + array[i].BorrowTime.substring(index1 + 1, index1 + 9);
					array[i].DueTime = array[i].DueTime.substring(0, index1) + " " + array[i].DueTime.substring(index1 + 1, index1 + 9);
				}
			},
			//去掉在库图书归还时间中的T
			formateBookOnData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].ReturnTime.indexOf("T");
					var index2 = array[i].BorrowTime.indexOf("T");
					array[i].ReturnTime = array[i].ReturnTime.substring(0, index1) + " " + array[i].ReturnTime.substring(index1 + 1, index1 + 9);
					array[i].BorrowTime = array[i].BorrowTime.substring(0, index1) + " " + array[i].BorrowTime.substring(index1 + 1, index1 + 9);
				}
			},
			//刷新
			reloadDatas() {
				if(this.activeName === 'first') {
					this.isReload = true;
					this.getUnReturnBookData();
				} else {
					this.isReload = true;
					this.findBookOnInfo();
				}
			},
			//查询用户为归还图书
			getUnReturnBookData() {
				HttpServer.httpGet.call(this, '/Api/Reader/BookHold?readercode=' + this.readerCode + '&index=' + this.unReturnCurrentPage + '&pageSize=' + this.unReturnPageSize, function(response) {}, function(response) {
					// console.log(response);
					if(response.data.code === 0) {
						this.formateData(response.data.info);
						this.unReturnTableData = response.data.info;
						this.unReturnTotalSize = response.data.totalcount;
						if(this.isReload){
							this.$notify({
								title: '成功',
								message: this.$t('message.refreshSuccess'),
								type: 'success',
								duration: 2500
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
					this.isReload = false;
				});
			},
			//查询当前在库图书
			findBookOnInfo() {
				if(this.keyWord != '') {
					this.item.value = this.keyWord;
					if(JSON.stringify(this.searchHistory).indexOf(JSON.stringify(this.item)) == -1) {
						if(this.searchHistory.length === 7) {
							this.searchHistory.splice(0, 1);
						}
						this.searchHistory.push(this.item);
						GloabFun.setSearchBook(JSON.stringify(this.searchHistory));
						this.$nextTick(function() {
							this.searchHistory = JSON.parse(GloabFun.getSearchBook());
						})
					}
				}
				var param = {
					index: this.currentBookOnPage,
					pageSize: this.pageBookOnSize,
					key: this.value === 0 ? this.keyWord : '',
					bookcode: this.value === 1 ? this.keyWord : '',
					tagcode: this.value === 2 ? this.keyWord : '',
					UserId: parseInt(GloabFun.getKeyId()),
					readercode: this.readerCode,
					sn:''
				}

				HttpServer.httpPost.call(this, '/Api/Book/AllBookOnByReader', param ,function(response) {}, function(response) {
					if(response.data.code === 0) {
							this.formateBookOnData(response.data.info);
							this.bookOnTableData = response.data.info;
							this.totalBookOnSize = response.data.totalcount;
							if(this.isReload){
								this.$notify({
									title: '成功',
									message: this.$t('message.refreshSuccess'),
									type: 'success',
									duration: 2500
								});
							}
						} else {
							this.$notify.error({
								title: '错误',
								message: response.data.msg,
								duration: 2500
							});
						}
						this.isReload = false;
					})	
			},
			//查询读者的未归还书籍信息及读者信息
			findUnReturnInfo() {
				if(this.readerCode == '') {
					this.$notify({
						title: '提示',
						message: '请输入读者条码',
						type: 'warning'
					});
				} else if(this.activeName == 'first'){
					this.loading = true;
					HttpServer.httpPost.call(this, '/Api/Reader/Info', {
						code: this.readerCode
					}, function(response) {}, function(response) {
						this.loading = false;
						if(response.data.code === 0) {
							if(response.data.info.length === 0) {
								this.readerInfo.splice(0, this.readerInfo.length);
								this.$notify.error({
									title: '错误',
									message: '该读者不存在',
									duration: 2500
								});
							} else {
								this.readerInfo = response.data.info;
								this.readerInfoName = response.data.info[0].name;
								this.readerInfoTag = response.data.info[0].tag;
								this.holdLimit = response.data.info[0].holdlimit;
								this.getUnReturnBookData();
							}
						}
					});
				}else {
					this.findBookOnInfo();
				}
			},
		},
		created() {
			var str = GloabFun.getSearchBook();
			if(str != '') {
				this.searchHistory = JSON.parse(str);
			} else {
				this.searchHistory = [];
			}
		}
	}
</script>
<style scoped>
	@import '../../../../../assets/css/font-awesome-4.7.0/css/font-awesome.css';
</style>
<style scoped lang="less">
	.name {
		color: #20a0ff;
	}
	
	.el-date-editor.el-input {
		width: 130px;
	}
	
	.edit-mission {
		padding-top: 50px;
		.el-dialog__header {
			background-color: #000;
		}
		.el-dialog__body {
			position: relative;
		}
		.clearfloat {
			height: 100px;
			max-height: 150px;
		}
	}
</style>